package com.guokeai.cookie;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author
 * @create 2021-04-22 21:19
 */
public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        //1 获取下载文件的路径
//        String realPath = this.getServletContext().getRealPath("/王可爱.png");
//        //注意：这个路径是E:\Java\Tomcat\apache-tomcat-10.0.5\webapps\response_war\王可爱.png
//        //不是E:\Java\JavaWeb\kuang_javaweb\response\src\main\resources\王可爱.png
//        System.out.println(realPath);

        String realPath = "E:\\Java\\JavaWeb\\kuang_javaweb\\response\\src\\main\\resources\\王可爱.png";
        //2 获取下载的文件名
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        //3 设置浏览器支持下载想要下载的文件,中文文件名URLEncoder.encode编码，否则有可能乱码
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        //4 获取下载文件的输入流
        FileInputStream fileInputStream = new FileInputStream(realPath);
        //5 创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //6 获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        //7 将FileInputStream流写入buffer缓冲区，使用OutputStream将缓冲区的数据输出到客户端
        while ((len = fileInputStream.read(buffer)) > 0){
            out.write(buffer,0,len);
        }

        out.close();
        fileInputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
